package com.gohome.gohomechat.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.gohome.gohomechat.GoHomeModel;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by dllo on 16/3/11.
 */
public class ImageUtil {
    public static String cacheDir = "";

    //初始化写在构造方法里
    public static String path() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File root = Environment.getExternalStorageDirectory();
            //想存在自己建的文件夹
            File cacheFile = new File(root.getAbsolutePath() + "/cache");
            //  Log.d("DiskCache11", "cacheFile:" + cacheFile);
            if (!cacheFile.exists()) {
                cacheFile.mkdir();
            }
            return cacheDir = cacheFile.getAbsolutePath();
            //    Log.d("DiskCache", cacheDir);
        }
        return "";
    }

    public void putBitmap(String url, Bitmap bitmap) {
        //   if (url.contains(".jpg")) {
        //   url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(cacheDir + url);
            compressImageByPixel(bitmap, cacheDir + url);
            // bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //   }
    }

    /**
     * 多线程压缩图片的质量
     *
     * @param bitmap  内存中的图片
     * @param imgPath 图片的保存路径
     * @author JPH
     * @date 2014-12-5下午11:30:43
     */

    public static void compressImageByQuality(final Bitmap bitmap, String imgPath) {

//        new Thread(new Runnable() {//开启多线程进行压缩处理
//            @Override
//            public void run() {
//                // TODO Auto-generated method stub
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//质量压缩方法，把压缩后的数据存放到baos中 (100表示不压缩，0表示压缩到最小)
        while (baos.toByteArray().length / 1024 > 100) {//循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即让下一次的写入覆盖之前的内容
            options -= 10;//图片质量每次减少10
            if (options < 0) options = 0;//如果图片质量小于10，则将图片的质量压缩到最小值
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//将压缩后的图片保存到baos中
            if (options == 0) break;//如果图片的质量已降到最低则，不再进行压缩
        }
        GoHomeModel.getInstance().setHead(imgPath);
        GoHomeModel.getInstance().setHeadByte(baos.toByteArray());
        try {
            FileOutputStream fos = new FileOutputStream(new File(imgPath));//将压缩后的图片保存的本地上指定路径中
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //   }).start();
    }

    /**
     * 按比例缩小图片的像素以达到压缩的目的
     *
     * @param imgPath
     * @author JPH
     * @date 2014-12-5下午11:30:59
     */
    public static void compressImageByPixel(Bitmap bitmap, String fileName) {
        path();
        FileOutputStream fos = null;
        try {
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            newOpts.inJustDecodeBounds = true;//只读边,不读内容
            fos = new FileOutputStream(cacheDir + fileName);


            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            bitmap = BitmapFactory.decodeFile(cacheDir + fileName, newOpts);
            //   Bitmap bitmap = BitmapFactory.decodeFile(filepath, newOpts);
            newOpts.inJustDecodeBounds = false;
            int width = newOpts.outWidth;
            int height = newOpts.outHeight;
            float maxSize = 1000f;//默认1000px
            int be = 1;
            if (width > height && width > maxSize) {//缩放比,用高或者宽其中较大的一个数据进行计算
                be = (int) (newOpts.outWidth / maxSize);
            } else if (width < height && height > maxSize) {
                be = (int) (newOpts.outHeight / maxSize);
            }
            be++;
            newOpts.inSampleSize = be;//设置采样率
            newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888;//该模式是默认的,可不设
            newOpts.inPurgeable = true;// 同时设置才会有效
            newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收
            //    bitmap = BitmapFactory.decodeFile(filepath, newOpts);


            bitmap = BitmapFactory.decodeFile(cacheDir + fileName, newOpts);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        compressImageByQuality(bitmap, cacheDir + fileName);//压缩好比例大小后再进行质量压缩
        // bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);

    }
}
